package com.qiyuexinxi.chat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiyuexinxi.chat.domain.District;
import com.qiyuexinxi.chat.dto.response.GetDistrictListResponse;
import com.qiyuexinxi.chat.exception.reg.exception.BizException;
import com.qiyuexinxi.chat.mapper.DistrictMapper;
import com.qiyuexinxi.chat.service.DistrictService;
import com.qiyuexinxi.chat.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author yangxingyu
 * @date 2020/3/10
 * @description
 */
@Service
public class DistrictServiceImpl implements DistrictService {

    private final static String districtList = "good-chat:districtList";

    @Autowired
    DistrictMapper districtMapper;

    @Override
    public List<GetDistrictListResponse> getDistrictList() {
        List<GetDistrictListResponse> getDistrictListResponses = null;
        //在redis中获取数据
        String districtLists = RedisUtil.StringOps.get(districtList);
        //如果没有获取到数据，在数据库中获取数据，并且放到redis中
        if(districtLists==null){
            getDistrictListResponses = getDistrictListByDB();
            String s = JSON.toJSONString(getDistrictListResponses);
            RedisUtil.StringOps.set(districtList,s);
            return getDistrictListResponses;
        }
        getDistrictListResponses = JSONObject.parseArray(districtLists, GetDistrictListResponse.class);
        return getDistrictListResponses;
    }

    @Override
    public boolean refreshDistrictList() {
        try {
            String s = JSON.toJSONString(getDistrictListByDB());
            RedisUtil.StringOps.set(districtList,s);
        }catch (Exception e){
            throw  new BizException("刷新redis区域列表异常",e);
        }
        return true;
    }

    public List<GetDistrictListResponse> getDistrictListByDB(){
        List<GetDistrictListResponse> getDistrictListResponses = new ArrayList<GetDistrictListResponse>();
        List<District> districts = districtMapper.selectList();
        for (District district:districts) {
            //获取省份
            String province = districtMapper.selectByPrimaryKey(district.getPid()).getDistrictName();
            getDistrictListResponses.add(new GetDistrictListResponse(district.getId()+"",province,district.getDistrictName()));
        }
        return getDistrictListResponses;
    }

}
